package com.ley.yikang.controller;

import com.ley.yikang.Annotation.UserLoginToken;
import com.ley.yikang.util.ResultData;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/File")
public class FileUploadController {
    // 时间格式化
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    // 图片保存路径，自动从配置文件中获取数据
    // 示例： ./src/main/resources/images/
    //@Value("${file-save-path}")
    //private String fileSavePath;

    @UserLoginToken
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultData<String> upload(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        // 1. 生成后半段目录：2020/03/15
        String directory = simpleDateFormat.format(new Date());

        // 2. 文件保存目录：./src/main/resources/images/2020/03/15/
        // 如果目录不存在，则创建
        File dir = new File(System.getProperty("user.dir") + "images/" + directory);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("图片上传，保存位置：" + System.getProperty("user.dir") + "images/" + directory);
        // 3. 给文件重新设置一个名字
        // 后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        // 4. 创建新文件
        File newFile = new File(System.getProperty("user.dir") + "images/" + directory + newFileName);
        // 5. 复制操作
        try {
            file.transferTo(newFile);
            // 6. 生成访问URL
            // 协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            return ResultData.success(url, "图片上传成功！");
        } catch (IOException e) {
            System.out.println(e.toString());
            return ResultData.fail("图片上传失败！" + e.toString());

        }
    }
}